// pages/game/game.js

const music = wx.createInnerAudioContext({
  useWebAudioImplement: false
})
music.src = 'http://music.163.com/song/media/outer/url?id=2089730107.mp3';

const util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    gametime: 30,
    showSS1: true,
    bigRound: null, // 大轮数初始为0
    smallRound: 1, // 小轮数初始为1
    showFail: false,
    showX: false,
    TIME: null,
    countDown: true,
    selId: '',
    topicPicture: '',
    answers: [],
    selectedAnswer: '',
    num: '',
    showSucceed: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.getRandomTopicID();
    this.getBigRound();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.foo(3); // 开始首个 3 秒倒计时阶段
    music.play();
  },

  /**
   * 倒计时功能,实现页面加载时的3秒和游戏倒计时
   * @param {number} totalTime - 总倒计时时间，单位为秒
   */
  foo: function (totalTime) {
    //递归函数，用于实现倒计时功能。
    const countDown = (time) => {
      if (time < 0) {
        clearTimeout(this.data.TIME);
        if (totalTime == 3) {
          this.setData({
            countDown: false
          });
          this.foo(this.data.gametime); // 开始下一个 50 秒倒计时阶段
        } else {
          this.setData({
            showFail: true,
            smallRound: 1,
          })
        }
        return;
      }
      this.setData({
        time: time,
      });
      this.data.TIME = setTimeout(() => {
        countDown(time - 1);
      }, 1000);
    };
    countDown(totalTime);
  },

  /**
   * 向后端发起请求，获取 bigRound 值，并计算关卡数
   */
  getBigRound: function () {
    util.request(getApp().globalData.requestUrl + 'users/GetLv', 'GET')
      .then(res => {
        this.setData({
          bigRound: res.data,
          num: res.data * 5 + this.data.smallRound
        });
      })
      .catch(err => {
        console.error('获取 bigRound 失败：', err.message);
      });
  },

  /**
   * 向后端发起请求，更新 biground 值到数据库
   * @param {number} biground - 要更新的 biground 值
   */
  updatebiground: function (biground) {
    util.request(getApp().globalData.requestUrl + 'users/UpdateLv', 'POST', {
        newData: biground
      })
      .then(res => {
        console.log('biground 更新成功');
      })
      .catch(err => {
        console.error('更新 biground 失败:', err.message);
      });
  },

  /**
   * 生成未使用过的 TopicID
   * @param {array} usedTopicIDs - 已使用的 TopicID 数组
   * @returns {number} -未使用过的 TopicID
   */
  generateUniqueRandomTopicID: function (usedTopicIDs) {
    let min = 101;
    let max = 129;
    let randomTopicID;
    do {
      randomTopicID = Math.floor(Math.random() * (max - min + 1)) + min;
    } while (usedTopicIDs.includes(randomTopicID));
    return randomTopicID;
  },


  /**
   * 向后端发起请求，获取随机且不重复的 TopicID，且把获取到的存在缓存， 当TopicID列表长度超过29，清空缓存的列表
   */
  getRandomTopicID: function () {
    this.setData({
      selectedAnswer: '',
    })
    let usedTopicIDs = wx.getStorageSync('usedTopicIDs') || [];
    if (usedTopicIDs.length >= 29) {
      wx.removeStorageSync('usedTopicIDs');
      usedTopicIDs = [];
    }
    let topicID = this.generateUniqueRandomTopicID(usedTopicIDs);
    util.request(getApp().globalData.requestUrl + 'game/GetTopicData', 'GET', {
        TopicID: topicID
      })
      .then(res => {
        const {
          data
        } = res;
        this.setData({
          topicPicture: data.TopicPicture,
          answers: data.Answer
        });
        usedTopicIDs.push(topicID);
        wx.setStorageSync('usedTopicIDs', usedTopicIDs);
      })
      .catch(err => {
        console.error('获取 TopicID 失败:', err.message);
      });
  },

  /**
   * 更新单选框选中的AnswerID
   * @param {object} e - 事件对象，包含选择的AnswerID
   */
  radioChange(e) {
    const selectedAnswerID = e.detail.value;
    this.setData({
      selectedAnswer: selectedAnswerID
    });
  },

  /**
   * 判断选择的答案是否正确，根据对错，轮次更改相应的数据
   */
  QueRen: function () {
    const selectedAnswer = this.data.selectedAnswer;
    if (!selectedAnswer) {
      wx.showToast({
        title: '请选择一个答案',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    const correctAnswer = this.data.answers.find(answer => answer.Judge == 'T');
    if (selectedAnswer == correctAnswer.AnswerID) {
      let smallRound = this.data.smallRound + 1;
      let bigRound = this.data.bigRound;
      if (smallRound > 5) {
        // 大轮次逻辑
        const hssComponent = this.selectComponent('#hss');
        if (hssComponent) {
          hssComponent.updateCoinAmount();
        } else {
          console.error('未找到hss组件实例');
          return;
        }
        clearTimeout(this.data.TIME);
        this.setData({
          showSS5: false,
          showSS6: true,
          showSucceed: true,
          bigRound: bigRound + 1,
          smallRound: 1,
          time: this.data.time,
        });
      } else {
        // 小轮次逻辑
        this.getRandomTopicID();
        let updateData = {
          [`showSS${smallRound - 1}`]: false,
          [`showSS${smallRound}`]: true,
          smallRound: smallRound,
          num: bigRound * 5 + smallRound
        };
        for (let i = 1; i <= 5; i++) {
          updateData[`showSS${i}`] = i === smallRound;
        }
        this.setData(updateData);
      }
    } else {
      // 回答错误的逻辑
      clearTimeout(this.data.TIME);
      this.setData({
        showFail: true,
        smallRound: 1,
        time: this.data.time,
      });
    }
  },

  /**
   * 继续闯关按钮
   */
  Continue: function () {
    this.foo(this.data.gametime);
    this.setData({
      bigRound: this.data.bigRound + 1,
      smallRound: 1,
      num: this.data.bigRound * 5 + this.data.smallRound,
      showSS1: true,
      showSS6: false,
      showSucceed: false,
    });
    this.updatebiground(this.data.bigRound);
    this.getRandomTopicID();
  },

  /**
   * 重新闯关按钮
   */
  restart: function () {
    this.setData({
      num: this.data.bigRound * 5 + this.data.smallRound,
      showSS1: true,
      showSS2: false,
      showSS3: false,
      showSS4: false,
      showSS5: false,
      showFail: false,
    });
    this.foo(this.data.gametime);
    this.getRandomTopicID(); // 获取新题目数据
  },

  /**
   * X按钮，退出游戏
   */
  GoToBack() {
    clearTimeout(this.data.TIME);
    this.setData({
      time: this.data.time,
      showX: true,
    });
  },

  /**
   * 确认返回按钮，回到首页
   */
  GoToBack2() {
    music.stop();
    wx.navigateTo({
      url: '/pages/index/index',
    })
  },

  /**
   * 取消返回按钮
   */
  GoToBack3() {
    this.setData({
      showX: false,
    });
    this.foo(this.data.time);
  },

})